
<?php echo form_tag('po/save', array(
  'id'        => 'sf_admin_edit_form',
  'name'      => 'sf_admin_edit_form',
  'multipart' => true,
)) ?>

<?php echo object_input_hidden_tag($po, 'getId') ?>

<fieldset id="sf_fieldset_none" class="">
<?php
    if ($po->getReviseId()) { ?>
        <input type="hidden" name="po[revise_id]" id="po[revise_id]" value="<?php echo $po->getReviseId() ?>" >
<?}
?>
<div class="form-row">
  <?php echo label_for('po[pono]', __($labels['po{pono}']), 'class="required" ') ?>
  <div class="content<?php if ($sf_request->hasError('po{pono}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{pono}')): ?>
    <?php echo form_error('po{pono}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <!--Tien-->
  <?php $default = CommonValues::GenerateAutoNumber('PO', $po->getPono(), 'PO')   ?>
   
   <input name="po_pono_show" id="po_pono_show" value="<?php echo $default ?>" size="15" disabled="disabled" type="text">
   </div>
</div>

<div class="form-row">
  <?php echo label_for('po[mrno]', __($labels['po{mrno}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{mrno}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{mrno}')): ?>
    <?php echo form_error('po{mrno}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php
        $value = '';
        $MRobject = null;
        if ($po->getMrno()) {            
            if ($po->getCompcategory() ==CommonValues::$gCompCategory['key']['Main Component']) 
                $MRobject = MRPeer::retrieveByPK($po->getMrno());
            elseif ($po->getCompcategory() ==CommonValues::$gCompCategory['key']['Sub Component']) 
                $MRobject = MR2Peer::retrieveByPK($po->getMrno());
            else 
                $MRobject = MR3Peer::retrieveByPK($po->getMrno());
            $value = $MRobject->getMrno();
        }
  ?>
  <input name="po[mrno]" id="po_mrno" value="<?php echo $po->getMrno() ?>"  type="hidden">
  <input name="po[compcategory]" id="po_compcategory" value="<?php echo $po->getCompcategory() ?>"  type="hidden">
   <input name="po_mrno_show" id="po_mrno_show" value="<?php echo $value ?>" size="13" disabled="disabled" type="text"> 
  
    </div>
</div>

<div class="form-row">
  <?php echo label_for('po[category]', __($labels['po{category}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{category}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{category}')): ?>
    <?php echo form_error('po{category}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php if ($po->getCategory() == null) $po->setCategory(0); ?>
  <input name="po[category]" id="po_category" value="<?php echo $po->getCategory() ?>"  type="hidden">
   <input name="po_pono_show" id="po_pono_show" value="<?php echo CommonValues::$gMRCategory['value'][$po->getCategory()] ?>" size="13" disabled="disabled" type="text">
    </div>
</div>

<div class="form-row">
  <?php echo label_for('po[created_at]', __($labels['po{created_at}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{created_at}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{created_at}')): ?>
    <?php echo form_error('po{created_at}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php $value = object_input_date_tag($po, 'getCreatedAt', array (
  'rich' => true,
  'calendar_button_img' => '/sf/sf_admin/images/date.png',
  'control_name' => 'po[created_at]',
)); echo $value ? $value : '&nbsp;' ?>
    </div>
</div>
        
<div class="form-row">
  <?php echo label_for('po[exparrdate]', __($labels['po{exparrdate}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{exparrdate}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{exparrdate}')): ?>
    <?php echo form_error('po{exparrdate}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php $value = object_input_date_tag($po, 'getExparrdate', array (
  'rich' => true,
  'calendar_button_img' => '/sf/sf_admin/images/date.png',
  'control_name' => 'po[exparrdate]',
)); echo $value ? $value : '&nbsp;' ?>
    </div>
</div>



<div class="form-row">
  <?php echo label_for('po[paymentterm]', __($labels['po{paymentterm}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{paymentterm}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{paymentterm}')): ?>
    <?php echo form_error('po{paymentterm}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php $value = object_input_tag($po, 'getPaymentterm', array (
  'size' => 100,
  'control_name' => 'po[paymentterm]',
)); echo $value ? $value : '&nbsp;' ?>
    </div>
</div>

<div class="form-row">
  <?php echo label_for('po[supplier_id]', __($labels['po{supplier_id}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{supplier_id}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{supplier_id}')): ?>
    <?php echo form_error('po{supplier_id}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php $value = object_select_tag($po, 'getSupplierId', array (
  'related_class' => 'Supplier',
  'control_name' => 'po[supplier_id]',
      'peer_method'=> 'getSorted',
)); echo $value ? $value : '&nbsp;' ?>
    </div>
</div>

<div class="form-row">
  <?php echo label_for('po[shippedvia]', __($labels['po{shippedvia}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{shippedvia}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{shippedvia}')): ?>
    <?php echo form_error('po{shippedvia}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <!--Tien-->
<select name="po[shippedvia]"" id="po_shippedvia">
<?php
    $categorylist = CommonValues::$gPOShip['key'];
    $category = $po->getShippedvia()?  $po->getShippedvia(): 0;
    foreach ($categorylist as $key => $value)
    { 
    	echo '<option value="' . $value.'" ';
    	if ($value == $category) 
    	   echo  'selected="selected" >';
    	else echo '>';
    	echo $key;
    	echo '</option>';
    }
   ?>
   </select>
    </div>
</div>

<div class="form-row">
  <?php echo label_for('po[type]', __($labels['po{type}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{type}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{type}')): ?>
    <?php echo form_error('po{type}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

   
  <!--Tien-->
<select name="po[type]"" id="po_type">
<?php
    $categorylist = CommonValues::$gPOType['key'];
    $category =  $po->getType()?  $po->getType(): 0;
    foreach ($categorylist as $key => $value)
    { 
    	echo '<option value="' . $value.'" ';
    	if ($value == $category) 
    	   echo  'selected="selected" >';
    	else echo '>';
    	echo $key;
    	echo '</option>';
    }
   ?>
   </select>
</div>
</div>

<div class="form-row">
  <?php echo label_for('po[currency]', __($labels['po{currency}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{currency}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{currency}')): ?>
    <?php echo form_error('po{currency}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>
  
  <select name="po[currency]" id="po_currency">
    <?php
        $c = sfCultureInfo::getInstance(sfContext::getInstance()->getUser()->getCulture());
        $currencies = $c->getCurrencies();
        $po->setCurrency( $po->getCurrency()? $po->getCurrency(): 'USD');
        foreach ($currencies as $key=>$category) { ?>
    <option value="<?php echo $key;  if ($key == $po->getCurrency()) echo '" selected="1'?>"><?php echo $key ?></option>
    <?php } ?>
  </select>  
    </div>
</div>

<div class="form-row">
  <?php echo label_for('po[vat]', __($labels['po{vat}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{vat}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{vat}')): ?>
    <?php echo form_error('po{vat}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php $value = object_input_tag($po, 'getVat', array (
  'size' => 7,
  'control_name' => 'po[vat]',
  'onkeyup' =>'calcTotalPrice()',
  'onchange' =>'calcTotalPrice()',
  'style'=>"text-align:right"
)); echo $value ? $value : '&nbsp;' ?>
    </div>
</div>

<div class="form-row">
  <?php echo label_for('po[shipandhand]', __($labels['po{shipandhand}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{shipandhand}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{shipandhand}')): ?>
    <?php echo form_error('po{shipandhand}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

      <input name="po[shipandhand]" id="po_shipandhand" value="<? echo CommonValues::FormatCurrency($po->getShipandhand());?>" size="7" onkeyup="calcTotalPrice()" onchange="calcTotalPrice()"  style="text-align: right;" type="text">
    </div>
</div>

<div class="form-row">
  <?php echo label_for('po[other]', __($labels['po{other}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{other}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{other}')): ?>
    <?php echo form_error('po{other}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

      <input name="po[other]" id="po_other" value="<?echo CommonValues::FormatCurrency($po->getOther());?>" size="7" onkeyup="calcTotalPrice()" onchange="calcTotalPrice()" style="text-align: right;" type="text">
    </div>
</div>

<div class="form-row">
  <?php echo label_for('po[approvalstatus]', __($labels['po{approvalstatus}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{approvalstatus}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{approvalstatus}')): ?>
    <?php echo form_error('po{approvalstatus}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php  $status = $po->getApprovalstatus()?  $po->getApprovalstatus(): 0?> 
  <input type="text" name ="mr_show" id ="mr_show" disabled="1"  value="<?php echo CommonValues::$gMRApprovalStatus['value'][$status]?>">
  <input type="hidden" name ="po[approvalstatus]" id ="po_approvalstatus" value="<?php echo $status?>">
    </div>
</div>

<div class="form-row">
  <?php echo label_for('po[receivedstatus]', __($labels['po{receivedstatus}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('po{receivedstatus}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('po{receivedstatus}')): ?>
    <?php echo form_error('po{receivedstatus}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php  $status = $po->getReceivedstatus()?  $po->getReceivedstatus(): 0?> 
  <input type="text" name ="mr_show" id ="mr_show" disabled="1"  value="<?php echo CommonValues::$gPOReceivedStatus['value'][$status]?>">
  <input type="hidden" name ="po[receivedstatus]" id ="po_receivedstatus" value="<?php echo $status?>">
    </div>
</div>


</fieldset>

<!--Tien code here-->
<?php
    //get components list from MR
    $componentGroupId = $MRobject->getComponentgroupId();
    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
    $c->addAscendingOrderByColumn(ComponentsPeer::ID);
    $MRcomponentsList = ComponentsPeer::doSelect($c);
    //get information from PO exist
    $bPOExist = false;
    if ($po->getComponentgroupId()){
        $PoCompGroupId = $po->getComponentgroupId();
        $bPOExist= true;
    }    
?>
<table id ='added_components' "cellspacing="0" class="sf_admin_list">
<thead>
<tr>
      <th id="sf_admin_list_th_productcode" width="25%">Product Code
              </th>
      <th id="sf_admin_list_th_description" width="35%">Description
              </th>
      <th id="sf_admin_list_th_description" width="10%">Brand
              </th>       
      <th id="sf_admin_list_th_description" width="10%">Unit
              </th>
      <th id="sf_admin_list_th_description">Qty Outstanding</th>
      <th id="sf_admin_list_th_description">Qty To Order</th>
      <th id="sf_admin_list_th_description">Unit Price</th>
      <th id="sf_admin_list_th_description">Total Price</th>
</tr>
</thead>
<!--show component here-->
<?php  
if (isset($po->rowIds) && count($po->rowIds)) {
$count = count($po->rowIds);
    foreach ($po->rowIds as $key=>$id) { 
        $component1= ComponentPeer::retrieveByPK($id);?>
        <tr class="sf_admin_row_<?php echo $key%2?>">
            <input type="hidden" name="rowIds[]" id ="rowIds"  class = "ExistComponents" value="<? echo $component1->getId()?>"/>
            <td><?echo $component1->getProductcode()?></td> 
            <td><?echo $component1->getDescription()?></td>
            <td><?echo $component1->getBrand()?></td>
            <td><?echo $component1->getComponentunit()?></td>
            <td><input type="text" name="qtyrt[]" id ="qtyrt" size="5" class ="QTYRT" disabled value ="<?echo $po->qtyr[$key]?>">
            <input type="hidden" name="qtyr[]" id ="qtyr" size="5" class ="QTYR"  value ="<?echo $po->qtyr[$key]?>"></td>
            <td><input type="text" name="qtys[]" id ="qtys" size="5" class ="QTYS" onkeyup="calcTotalPrice()" onchange="calcTotalPrice()" value ="<?echo $po->qtys[$key] ?>"></td>
            <td><input type="text" name="unitprices[]" id ="unitprices" size="7" class = "UNITPRICE" onkeyup="calcTotalPrice()" onchange="calcTotalPrice()" value ="<?echo $po->unitprices[$key] ?>"></td>
            <td><input type="text" name="totalprices[]" id ="totalprices" size="9" readonly class = "TOTALPRICE" value ="<?echo $po->totalprices[$key]?>"></td>
        </tr>
<?} } elseif (isset($MRcomponentsList) && $MRcomponentsList && count($MRcomponentsList)) {

    $count = count($MRcomponentsList);
    foreach ($MRcomponentsList as $key=>$components) { 
        $component= ComponentPeer::retrieveByPK($components->getComponentId());
        //if there is this component existed in PO then get it
        $bExist = false;
        if ($bPOExist) {
            $c = new Criteria();
            $c->add(ComponentsPeer::COMPONENT_ID, $component->getId());
            $c->add(ComponentsPeer::COMPONENTGROUP_ID, $PoCompGroupId);
            $existComponents = ComponentsPeer::doSelectOne($c);
            $bExist= $existComponents? true: false;
        }
        
?>
        <tr class="sf_admin_row_<?php echo $key%2?>">
            <input type="hidden" name="rowIds[]" id ="rowIds"  class = "ExistComponents" value="<? echo $component->getId()?>"/>
            <td><?echo $component->getProductcode()?></td>
            <td><?echo $component->getDescription()?></td>
            <td><?echo $component->getBrand()?></td>
            <td><?echo $component->getComponentunit()?></td>
            <td><input type="text" name="qtyrt[]" id ="qtyrt" size="5" class ="QTYRT" disabled  style="text-align:right" value ="<?echo $components->getQty4()?>">
            <input type="hidden" name="qtyr[]" id ="qtyr" size="5" class ="QTYR"  style="text-align:right" value ="<?echo $components->getQty4()?>"></td>
            <td><input type="text" name="qtys[]" id ="qtys" size="5" class ="QTYS" style="text-align:right" onkeyup="calcTotalPrice()" onchange="calcTotalPrice()" value ="<?echo $bExist? $existComponents->getQty1() : '' ?>"></td>
            <td><input type="text" name="unitprices[]" id ="unitprices" size="7" style="text-align:right" class = "UNITPRICE" onkeyup="calcTotalPrice()" onchange="calcTotalPrice()" value ="<?echo $bExist? CommonValues::FormatCurrency($existComponents->getQty2()) : '' ?>"></td>
            <td><input type="text" name="totalprices[]" id ="totalprices" size="9" style="text-align:right" readonly class = "TOTALPRICE"    value ="<?echo $bExist? CommonValues::FormatCurrency($existComponents->getQty3()) : '' ?>"></td>
        </tr>
<?php } }?>
<tr class="sf_admin_row_<? echo $count % 2; ?>">
<td></td><td></td><td></td><td></td><td></td><td></td><td><b>Subtotal Price</b></td><td>
<input type="text" name ="po[subtotalprice]" id = 'po_subtotalprice' value ="<? echo CommonValues::FormatCurrency($po->getSubtotalprice()); ?>" size="9" readonly  style="text-align:right">
</td>
</tr>
<tr class="sf_admin_row_<? echo ($count+1) % 2; ?>">
    <td></td><td></td><td></td><td></td><td></td><td></td><td><b>Total Price</b></td><td><input type="text" name ="po[totalprice]" id = 'po_totalprice' value ="<? echo CommonValues::FormatCurrency($po->getTotalprice()); ?>" size="9" readonly  style="text-align:right"></td>
</tr>
</table>

<?php
//just affect to ajax
echo link_to_remote('', array('update' => 'list_component', 
  'url' => 'component/listAjax', 
  'loading' => visual_effect('appear', 'indicator'),
  'complete' => visual_effect('fade', 'indicator'). visual_effect('highlight', 'list_component'),
  'position' => 'bottom',
));
?>
<script type="text/javascript">


function calcTotalPrice(){

    var qtys = $$(".QTYS");
    var unitprices= $$(".UNITPRICE");
    var totalprices= $$(".TOTALPRICE");
    
    var sub= $("po_subtotalprice");
    var total= $("po_totalprice");
    
    var sub2= ConvertToNumber($("po_vat").value);
    if (!sub2) sub2 =0;
    var sub3= ConvertToNumber($("po_shipandhand").value);
    if (!sub3) sub3 =0;
    var sub4= ConvertToNumber($("po_other").value);
    if (!sub4) sub4 =0;
    
    var sub1 = 0;
    var total1=0;
    
    for (var i =0; i < qtys.length; i++){
        var unit_price = ConvertToNumber(unitprices[i].value);        
        if (qtys[i].value >0 &&  unit_price> 0) {
            totalprices[i].value = FormatCurrency(qtys[i].value * unit_price);
            sub1 += qtys[i].value * unit_price;
        }
        else totalprices[i].value= '';
    }

    sub.value = FormatCurrency(sub1);
    total1 +=sub1 + sub2*sub1/100 + sub3 + sub4;
    if (total1)
        total.value = FormatCurrency(total1);
}

function ConvertToNumber(num)
{
    num = String(num);
    num = num.replace(/[\$\,]/gi,'');
    return parseFloat(num);
}
function FormatCurrency(num) {
        num = String(num);
	num = num.replace(/[\$\,]/gi,'');
	i = num.indexOf('.');
	if (i==-1)
	{
		i = num.length;
	}
	tp = num.substring(i +1, num.length);
	num = num.substring(0, i);
	x='';
	for (var i=0; i < num.length ; i++)
	{
		if (i >0 && i % 3 ==0)
		{
			x = num[num.length - i -1] + ',' + x;
		}
		else x = num[num.length - i -1] + x;
	}
        if (tp != '')
            x+= '.' + tp;
        return x;
}
</script>

<?php include_partial('edit_actions', array('po' => $po)) ?>

</form>

<ul class="sf_admin_actions">
      <li class="float-left"><?php if ($po->getId()): ?>
<?php echo button_to(__('delete'), 'po/delete?id='.$po->getId(), array (
  'post' => true,
  'confirm' => __('Are you sure?'),
  'class' => 'sf_admin_action_delete',
)) ?><?php endif; ?>
</li>
  </ul>
